import Vue from 'vue'
import axios from 'axios';
import router from '../router';
import store from "../store";
import common from "../utils/common";
import { Toast } from 'vant';

Vue.use(Toast);


axios.defaults.timeout = 15000; //请求超时5秒
axios.defaults.baseURL = process.env.API_HOST;  //请求base url
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //设置post请求是的header信息

// axios.defaults.withCredentials = true

var _bus = new Vue()
var num = 0

//http request 拦截器
axios.interceptors.request.use(
  config => {
    let token = store.state.isApp ? store.state.appToken : localStorage.getItem('token');
    let lang = 'zh'

    let locale = localStorage.getItem("language") || "zh";
    if("jp" == locale){
      lang = "ja_JP";
    } else if ( "zh" == locale ) {
      lang = "zh_CN";
    }  else if ( "en" == locale ) {
      lang = "en_US";
    } else if ("ko_KR" == locale) {
      lang = "ko_KR";
    } else if ("th_TH" == locale) {
      lang = "th_TH";
    } else {
      lang = locale;
    }

    let timestamp = new Date().getTime();
    // let obj = new Object();


    if(config.isUpload){
      var obj = new Object();
    }else{
      var obj = Object.assign({}, config.data);
    }


    obj.timestamp = timestamp;
    obj.apiKey = "test";

    // 去掉签名对象里面的空值，未定义字段
    for ( var key in obj ){
      if ( obj[key] === '' || undefined === obj[key] || null === obj[key]){
        delete obj[key]
      }
    }
    obj.sign = common.sign(obj);


    if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      // 判断是否是upload模式，如果是则需要改为form-data格式
      // console.log("config = ", config);
      if (config.isUpload) {
        let formData = new FormData();//new一个formData事件
        formData.append("file",config.data.file);
        formData.append("sign",obj.sign);
        formData.append("timestamp",obj.timestamp);
        formData.append("apiKey",obj.apiKey);
        config.data = formData
        config.headers = {
          'Content-Type': 'multipart/form-data',
          system:'android',
          token,
          lang
        }
      } else {


        config.data = obj ;
        config.data = JSON.stringify(config.data)
        config.headers = {
          'Content-Type': 'application/json',
          system:'android',
          token,
          lang
        }
      }
      num++
      _bus.$emit('showloading')
    } else {
      config.data = obj ;
      config.headers = {
        'Content-Type': 'application/json',
        system:'android',
        lang
      }
    }

    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  response => {
    num--
    if (num <= 0) {
      _bus.$emit('closeLoading')
    } else {
      _bus.$emit('showloading')
    }
    if (response.data.code == 401) {
      Toast({
        message: 'Please login!',
        timeout: 1500,
      });
      if(!store.state.isApp){
        store.dispatch('resetVuex');
        router.push('/login')
      } else {
        let appResult = {
          code: response.data.code
        };
        common.callBackApp(appResult);
        return response;
      }
      // else app提供的方法

      // router.push({
      //   path:"/user/login",
      //   querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
      // })
      // setTimeout(function(){
      //   router.push({
      //     path:"/user/login",
      //     querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
      //   })
      // }, 1500);


      return response;
    }
    // if (response.data.code === -1) {
    //   localStorage.removeItem('token')
    //   router.push({
    //     path:"/login",
    //     querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
    //   })
    // }
    return response
  },
  err => {
    _bus.$emit('closeLoading')
    if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
      Toast({
        message: 'Time Out...',
        timeout: 1500
      });
    }
    return Promise.reject(err)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      headers: headers
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}, config = { isUpload: false }) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, config)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}0

export var bus = _bus

